// src/routes/securities/+page.ts
import type { GetParams, IpcResponse, KlineFlat, TradeBot, TradeOrder, TradeStrategy } from '$lib/bindings';
import type { PageLoad } from './$types';
import * as commands from '$lib/commands'
import { get_kline_flats, get_trade_bot, get_trade_orders } from '$lib/Backend';
import { updateHistoryStore } from '$lib/FudaStore';

export const load: PageLoad = async ({ url, route, params }) => {
    const { id } = params;
    console.log("(tbots/[id]/+page.ts) route=", route, " url=", url, " params=", params);
    let tradeBot: TradeBot | undefined = undefined;
    let tradeOrders: TradeOrder[] | undefined = [];
    let klineFlats: KlineFlat[] | null | undefined = undefined;
    let tradeStrategy: TradeStrategy | undefined = undefined;

    try {
        const res = await get_trade_bot(id)
        if (res) {
            tradeBot = res;

            if (tradeBot && tradeBot.strategy_id) {

                try {

                    // Define the argument
                    const args: GetParams = {
                        id: tradeBot.strategy_id.id.String, // "Tstg.DAY.0",
                    }

                    const res: IpcResponse<TradeStrategy> = await commands.get_trade_strategy(args)

                    console.log("(tbots/[id]/+page.ts) res=", res, " args=", args);

                    if (res.error) {
                        // If the response status is not OK, throw an error
                        throw new Error(`(tbots/[id]/+page.ts) Server returned an error: ${res.error}`);
                    }

                    // If the server response is empty, return sample data
                    if (res.result) {
                        tradeStrategy = res.result.data
                    }


                } catch (error) {
                    // If there's any error (e.g., network issue), return sample data
                    console.error('(tbots/[id]/+page.ts) Error fetching tbots:', error);

                }
            }

            if (tradeBot && tradeBot.security_id) {
                try {
                    klineFlats = await get_kline_flats(tradeBot.security_id.id.String, 'DAY', 0, 251); // Directly await the promise
                    if (klineFlats) {
                        let startKline = klineFlats.reduce((min, kline) => kline.klts < min.klts ? kline : min);
                        let endKline = klineFlats.reduce((max, kline) => kline.klts < max.klts ? max : kline);

                        try {
                            const t_orders = await get_trade_orders(id, startKline.id?.id.String || null, endKline.id?.id.String || null); // Directly await the promise
                            if (t_orders) {
                                tradeOrders = t_orders;
                            }
                        } catch (error) {
                            // If there's any error (e.g., network issue), return sample data
                            console.error('(tbots/[id]/+page.ts) Error fetching trade_orders:', error);
                        }
                    }
                } catch (error) {
                    // If there's any error (e.g., network issue), return sample data
                    console.error('(tbots/[id]/+page.ts) Error fetching trade_orders:', error);
                }
            }

            updateHistoryStore(res, null)
        }
    } catch (error) {
        // If there's any error (e.g., network issue), return sample data
        console.error('(tbots/[id]/+page.ts) Error fetching trade_orders:', error);
    }



    return {
        id: id,
        trade_bot: tradeBot,
        trade_orders: tradeOrders,
        klineFlats: klineFlats,
        tradeStrategy: tradeStrategy,
    };


};